package com.chenwei.transactional.aspect;

import com.chenwei.transactional.utils.CWTransactionalUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

/**事务切面
 * @author: chenwei
 * @date: 2021/4/2 22:53
 */
@Aspect
@Component
public class CWTransactionalASpect {

    @Autowired
    private CWTransactionalUtils cWTransactionalUtils;

    /**
     *  切加注解的目标方法
     * @author: chenwei
     * @date: 2021/4/2 23:16
     */
    @Around(value = "@annotation(com.chenwei.transactional.cwAnnotation.CWTransactional)")
    public Object around(ProceedingJoinPoint point){
        TransactionStatus begin =null;
        try {
            System.out.println("===事务开启===");
            begin = cWTransactionalUtils.begin();
            Object proceed = point.proceed();//目标方法执行
            System.out.println("===事务提交===");
            cWTransactionalUtils.commit(begin);
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("===事务回滚===");
            if(begin!=null){
                cWTransactionalUtils.rollBack(begin);
            }
            return "运行异常";
        }


    }
}
